<template>
    <el-drawer
      v-model="visible"
      title="数据导入"
      size="40%"
      direction="rtl"
      @closed="handleClose"
    >
      <div class="drawer-content">
        <el-upload
          class="upload-demo"
          action="/api/user/import"
          :headers="headers"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-progress="handleProgress"
          :before-upload="beforeUpload"
          :show-file-list="false"
          accept=".xlsx"
        >
          <el-button type="primary">点击上传用户数据</el-button>
          <template #tip>
            <div class="upload-tip">
              请上传.xlsx格式文件，文件大小不超过5MB
            </div>
          </template>
        </el-upload>

         <!-- 上传进度条 -->
      <div v-if="showProgress" class="progress-container">
        <el-progress 
          :percentage="uploadProgress" 
          :status="uploadStatus"
          stroke-width="8"
        />
        <div class="progress-text">
          {{ progressText }}
        </div>
      </div>
  
        <div class="template-download">
          <span>下载模板文件：</span>
          <el-button type="text" @click="downloadTemplate">用户数据模板.xlsx</el-button>
        </div>
  
        <el-dialog v-model="errorDialogVisible" title="导入错误" width="30%">
          <div style="color: red; white-space: pre-wrap">{{ errorMessage }}</div>
          <template #footer>
            <el-button @click="errorDialogVisible = false">关闭</el-button>
          </template>
        </el-dialog>
      </div>
    </el-drawer>
  </template>
  
  <script setup lang="ts">
  import { ref, watch,reactive,computed } from 'vue';
  import { ElMessage, UploadProps } from 'element-plus';
  import { userMangerApi } from  '@/api/user';
  import { useUserStore } from '@/store/user';
  const userStore = useUserStore()
  const { token } = userStore
  interface Props {
    modelValue: boolean;
  }
  
  interface Emits {
    (e: 'update:modelValue', value: boolean): void;
    (e: 'success'): void;
  }
  
  const props = defineProps<Props>();
  const emit = defineEmits<Emits>();
  
  const visible = ref(props.modelValue);
   // 定义上传图片头部
   const headers = reactive({
    Authorization: token || ''
  })

  // 进度条相关状态
const showProgress = ref(false);
const uploadProgress = ref(0);
const uploadStatus = ref<'success' | 'exception' | ''>('');

  // 计算属性显示进度文本
const progressText = computed(() => {
  if (uploadStatus.value === 'success') return '上传完成！';
  if (uploadStatus.value === 'exception') return '上传失败！';
  return `上传中... ${uploadProgress.value}%`;
});
  
  // 错误处理状态
  const errorDialogVisible = ref(false);
  const errorMessage = ref('');
  
  // 同步父组件状态
  watch(() => props.modelValue, (val) => {
    visible.value = val;
  });
  
  watch(visible, (val) => {
    emit('update:modelValue', val);
  });
  
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
     // 重置进度状态
    showProgress.value = false;
    uploadProgress.value = 0;
    uploadStatus.value = '';
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const isLt5M = file.size / 1024 / 1024 < 5;
    
    if (!isExcel) {
      ElMessage.error('只能上传.xlsx格式文件');
      return false;
    }
    if (!isLt5M) {
      ElMessage.error('文件大小不能超过5MB');
      return false;
    }
    // 验证通过后显示进度条
    showProgress.value = true;
    return true;
  };

  // 进度条显示
  const handleProgress: UploadProps['onProgress'] = (event) => {
   uploadProgress.value = Math.floor(event.percent);
};
  
// 导入成功事件
  const handleSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 1) {
        uploadStatus.value = 'success';
        setTimeout(() => {
        showProgress.value = false;
        ElMessage.success(response.msg);
        emit('success');
        visible.value = false;
        }, 1500);
    } else {
      uploadStatus.value = 'exception';
      errorMessage.value = response.msg || '未知错误';
      errorDialogVisible.value = true;
      setTimeout(() => {
      showProgress.value = false;
    }, 2000);
    }
  };
  
  const handleError: UploadProps['onError'] = () => {
    uploadStatus.value = 'exception';
    ElMessage.error('文件上传失败，请检查网络连接');
    setTimeout(() => {
    showProgress.value = false;
  }, 2000);
  };
  
  // 下载模板
  const downloadTemplate = async () => {
    try {
      const response = await userMangerApi.downloadTemplate();
      const filename = '用户导入模板.xlsx';
  
      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      ElMessage.error('模板下载失败');
      console.error('下载错误:', error);
    }
  };
  
  const handleClose = () => {
    errorDialogVisible.value = false;
    errorMessage.value = '';
  };
  </script>
  
  <style scoped>

  /* 新增进度条样式 */
.progress-container {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.progress-text {
  margin-top: 8px;
  text-align: center;
  font-size: 12px;
  color: #909399;
}
  .drawer-content {
    padding: 20px;
  }
  
  .upload-demo {
    margin: 20px 0;
  }
  
  .upload-tip {
    margin-top: 10px;
    color: #999;
    font-size: 12px;
  }
  
  .template-download {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }
  </style>